import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import type {
  CountStateType,
  CountStateActionType,
  LanguageType,
  LanguageStateType,
  LanguageStateActionType,
  ThemeType,
  ThemeStateType,
  ThemeStateActionType,
  MetaStateType,
  MetaStateActionType,
  MenuStateType,
  MenuStateActionType,
} from './index.type'

// 示例
/** 计数状态存储 */
const useCountState = create<CountStateType & CountStateActionType>()(
  persist(
    (set, get) => ({
      count: 0,
      addCount: () => set({ count: get().count + 1 }),
    }),
    {
      name: 'count-storage', // 存储的名称、必须唯一
      storage: createJSONStorage(() => sessionStorage),
      // name: 存储中使用的唯一键名
      // storage: 自定义存储引擎
      // partialize: 选择存储部分状态字段
      // onRehydrateStorage: 在存储被重新加载之后触发
      // version: 版本控制
      // migrate: 处理版本迁移的函数
      // merge: 自定义持久化的值与当前状态的合并方式
      // skipHydration: 是否跳过初始化时的自动恢复
    }
  )
)

/** 语言状态存储 */
const useLanguage = create<LanguageStateType & LanguageStateActionType>()(
  persist(
    (set) => ({
      language: 'zh-CN',
      setLanguage: (language: LanguageType) => set({ language }),
      resetLanguage: () => set({ language: 'zh-CN' }),
    }),
    {
      name: 'language-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 主题状态存储 */
const useTheme = create<ThemeStateType & ThemeStateActionType>()(
  persist(
    (set) => ({
      theme: 'light',
      setTheme: (theme: ThemeType) => set({ theme }),
      resetTheme: () => set({ theme: 'light' }),
    }),
    {
      name: 'theme-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 元数据存储 */
const useMeta = create<MetaStateType & MetaStateActionType>()(
  persist(
    (set, get) => ({
      meta: {
        title: '',
        keywords: '',
        description: '',
      },
      setMeta: (title: string, keywords?: string, description?: string) => {
        document.title = title
        set({
          meta: {
            title,
            keywords: keywords || title,
            description: description || title,
          }
        })
      },
    }),
    {
      name: 'meta-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
)

/** 菜单键存储 */
const useMenuKey = create<MenuStateType & MenuStateActionType>()(
  persist(
    (set, get) => ({
      menuKey: '/home',
      setMenuKey: (menuKey: string) => set({ menuKey }),
    }),
    {
      name: 'menu-key-storage',
      storage: createJSONStorage(() => sessionStorage),
    }
  )
)

export {
  useCountState,
  useLanguage,
  useTheme,
  useMeta,
  useMenuKey,
}